package marksys.free.com.marksys.ui.face.facebykomlinplus;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;

import java.io.IOException;
import java.util.List;

public class CameraInterface {
    private static final String TAG = "CameraInterface";
    CamOpenOverCallback callback;
    Context context;

    public Camera getmCamera() {
        return mCamera;
    }

    private Camera mCamera;
    private Camera.Parameters mParams;

    private boolean isPreviewing = false;
    private float mPreviwRate = -1f;
    private static CameraInterface mCameraInterface;

    public interface CamOpenOverCallback {
        void cameraHasOpened();
    }

    Handler handler;
    public static int MSG_AUTOFUCS_0 = 0;

    private CameraInterface() {

    }

    public static synchronized CameraInterface getInstance() {
        if (mCameraInterface == null) {
            mCameraInterface = new CameraInterface();
        }
        return mCameraInterface;
    }

    public int getCameraId() {
        return cameraId;
    }


    public void setCameraId(int cameraId) {
        this.cameraId = cameraId;
        doStopCamera();
        doOpenCamera(context, callback);
    }

    private int cameraId = 0;


    public int getPictureDegrees() {
        return pictureDegrees;
    }

    private int pictureDegrees;

    /**
     * 打开Camera
     *
     * @param callback
     */
    public void doOpenCamera(Context activity, CamOpenOverCallback callback) {
        Log.i(TAG, "Camera open....");
        this.callback = callback;
        this.context = activity;
        if (ContextCompat.checkSelfPermission(activity, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions((Activity) activity, new String[]{android.Manifest.permission.CAMERA}, 1);
            Log.e(TAG, "Camera open requestPermissions");
        } else {

            mCamera = Camera.open(cameraId);
            setCameraDisplayOrientation((Activity) activity, cameraId, mCamera);
            Log.i(TAG, "Camera open over....");
            callback.cameraHasOpened();
        }

    }

    /**
     * 保证视频流是正向的。
     */
    public void setCameraDisplayOrientation(Activity activity,
                                            int cameraId, Camera camera) {
        Camera.CameraInfo info =
                new Camera.CameraInfo();
        Camera.getCameraInfo(cameraId, info);
        pictureDegrees = info.orientation;

        int rotation = activity.getWindowManager().getDefaultDisplay()
                .getRotation();
        int degrees = 0;
        switch (rotation) {
            case Surface.ROTATION_0:
                degrees = 0;
                break;
            case Surface.ROTATION_90:
                degrees = 90;
                break;
            case Surface.ROTATION_180:
                degrees = 180;
                break;
            case Surface.ROTATION_270:
                degrees = 270;
                break;
        }

        int result;
        if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
            result = (info.orientation + degrees) % 360;
            result = (360 - result) % 360;  // compensate the mirror
        } else {  // back-facing
            result = (info.orientation - degrees + 360) % 360;
        }
        camera.setDisplayOrientation(result);
    }


    /**
     * 开启预览
     *
     * @param holder
     */
    @SuppressLint("HandlerLeak")
    public void doStartPreview(Context context, SurfaceHolder holder, CameraSurfaceView surfaceView) {
        Log.i(TAG, "doStartPreview...");
        if (isPreviewing) {
            mCamera.stopPreview();
            return;
        }
        if (mCamera != null) {

            mParams = mCamera.getParameters();


            mParams.setPictureFormat(PixelFormat.JPEG);//设置拍照后存储的图片格式

            List<String> focusModes = mParams.getSupportedFocusModes();
            if (focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
                // Autofocus mode is supported
                mParams.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
            }


            Resources resources = context.getResources();
            DisplayMetrics dm = resources.getDisplayMetrics();
            float density = dm.density;
            int screenWidth = dm.widthPixels;
            int screenHeight = dm.heightPixels;


            Camera.Size preSize = CamParaUtil.getCloselyPreSize(true, screenWidth, screenHeight, mParams.getSupportedPreviewSizes());
            //Camera.Size preSize = CamParaUtil.getCloselyPreSize(mParams.getSupportedPreviewSizes());
            mParams.setPreviewSize(preSize.width, preSize.height);


            // 横竖屏镜头自动调整
            if (context.getResources().getConfiguration().orientation != Configuration.ORIENTATION_LANDSCAPE) {
                mParams.set("orientation", "portrait"); //
                mParams.set("rotation", 90); // 镜头角度转90度（默认摄像头是横拍）
                mCamera.setDisplayOrientation(90); // 在2.2以上可以使用
            } else// 如果是横屏
            {
                mParams.set("orientation", "landscape"); //
                mCamera.setDisplayOrientation(0); // 在2.2以上可以使用
            }
            mCamera.setParameters(mParams);  //参数设置完毕

            try {
                mCamera.setPreviewDisplay(holder);
            } catch (IOException e) {
                e.printStackTrace();
            }

            mCamera.startPreview();//开启预览


            isPreviewing = true;


        }
    }


    /**
     * 停止预览，释放Camera
     */
    public void doStopCamera() {
        if (null != mCamera) {
            mCamera.setPreviewCallback(null);
            mCamera.stopPreview();
            isPreviewing = false;
            mCamera.release();
            mCamera = null;
        }
    }

}
